<template>
  <div class="type-container app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.id_public_goods_type" placeholder="分类ID" clearable class="filter-item input-item"
        style="width: 200px;" @clear="handleFilter" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.type_name" placeholder="分类名称" clearable class="filter-item input-item"
        style="width: 200px;" @clear="handleFilter" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="分类ID" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id_public_goods_type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.is_online"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="handleChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="位置操作" align="center">
        <template slot-scope="{row}">
          <div>
            <el-tooltip class="item" effect="dark" content="上移" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-arrow-up" circle @click="moveData('up', row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="下移" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-arrow-down" circle @click="moveData('down', row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="置顶" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-upload2" circle @click="moveDataEnd('up', row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="置底" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-download" circle @click="moveDataEnd('down', row)" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="业务操作" align="center">
        <template slot-scope="{row}">
          <el-button size="small" type="primary">
            <router-link :to="{path: '/goods/typeChild/'+row.id_public_goods_type+'/'+row.type_name}">
              子分类
            </router-link>
          </el-button>
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="currentPage" :limit.sync="listQuery.limit"
      @pagination="getPageList" />

    <el-dialog :title="textMap[dialogStatus] + '分类'" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px">
        <el-row :gutter="40">
          <el-col>
            <el-form-item label="分类名称" prop="type_name">
              <el-input v-model="temp.type_name" maxlength="10" show-word-limit placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col>
            <el-form-item label="分类描述" prop="agent_phone">
              <el-input v-model="temp.type_describe" maxlength="15" show-word-limit placeholder="请输入分类描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { goodsList } from '@/api/goods'
import { warehouseList } from '@/api/warehouse'

export default {
  name: 'TypeList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      currentPage: 0,
      defaultWeight: 0,
      listQuery: {
        invoke_method: 'public_page_4m_load_main_cls',
        filter_type: 1,
        // is_online: 0,
        pre_db_para_open_time_require_select: 0,
        pre_cmd_para_show_admin_type: 'super_and_login',
        pre_db_para_begin_idx: 0,
        pre_db_para_length_4_list: 10,
        pre_db_para_type_name: null,
        pre_db_para_id_public_goods_type: null,
        pre_db_para_order_by_para: 'data_weight desc'
      },
      childDisable: true,
      typeFather: [],
      typeChild: [],
      filterType: [
        { value: 1, label: '常用商品服务' },
        { value: 5, label: '充值付费商品' },
        { value: 11, label: '样品类' }
      ],
      temp: {
        invoke_method: null,
        pre_db_para_id_public_goods_type: null,
        type_name: null,
        type_describe: null,
        type_father: -1,
        filter_type: 1,
        is_online: 0,
        id_public_data_admin_user: 800
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        type_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  mounted() {
    if (this.$route.query.agent_id) {
      this.listQuery.buyer_id = this.$route.query.agent_id
    }
    this.getList()
  },
  methods: {
    /*
    * 获取页面数据
    * */
    getList() {
      this.listLoading = true
      goodsList(this.Qs.stringify(this.listQuery)).then(response => {
        this.list = response.page_content
        this.total = response.num_view

        if (this.list.length) {
          this.defaultWeight = this.list[0].data_weight + 10
        } else {
          this.defaultWeight = 1000
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },

    /*
    * 点击分页进行查询
    * */
    getPageList(val) {
      this.listQuery.pre_db_para_begin_idx = (val.page - 1) * this.listQuery.pre_db_para_length_4_list
      this.getList()
    },
    /*
    * 查询数据
    * */
    handleFilter() {
      this.listQuery.pre_db_para_begin_idx = 0
      this.getList()
    },
    clearFilter() {
      this.listQuery.pre_db_para_begin_idx = 0
      this.listQuery.filter_type = 1
      this.getList()
    },
    selectFilter(val) {
      if (val) {
        this.getList()
        this.getTypeFather(val)
      } else {
        this.getTypeFather(1)
      }
    },
    /*
    * 上移下移
    * */
    moveData(type, item) {
      goodsList(this.Qs.stringify({
        id_public_goods_type: item.id_public_goods_type,
        pre_cmd_para_move_direction_type: type,
        invoke_method: 'public_page_4m_move_type'
      })).then(response => {
        this.$notify({
          title: 'Success',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    // 置顶置底
    moveDataEnd(type, item) {
      goodsList(this.Qs.stringify({
        id_public_goods_type: item.id_public_goods_type,
        pre_cmd_para_move_direction_type: type,
        invoke_method: 'public_page_4m_move_type_2_end'
      })).then(response => {
        this.$notify({
          title: 'Success',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    /*
    * 新增/编辑数据
    * */
    resetTemp() {
      this.temp = {
        invoke_method: null,
        type_name: null,
        type_describe: null,
        type_father: -1,
        filter_type: 1,
        is_online: 0,
        id_public_data_admin_user: 800
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.updateData()
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          /*
          * duzikai_api_mgr_public_goods_info?invoke_method=public_page_4m_insert_or_update_goods_type&pre_db_para_id_public_goods_type=53&type_name=粮油类1111&type_father=-1&is_online=0&data_weight=3911&type_describe=123
          * */
          let params;
          if (this.dialogStatus === 'create') {
            params = {
              invoke_method: 'public_page_4m_insert_or_update_goods_type',
              type_name: this.temp.type_name,
              type_father: this.temp.type_father,
              type_describe: this.temp.type_describe,
              is_online: this.temp.is_online,
              filter_type: 1,
              data_weight: this.defaultWeight
            }
          } else {
            params = {
              invoke_method: 'public_page_4m_insert_or_update_goods_type',
              pre_db_para_id_public_goods_type: this.temp.id_public_goods_type,
              type_name: this.temp.type_name,
              type_father: this.temp.type_father,
              type_describe: this.temp.type_describe,
              is_online: this.temp.is_online,
            }
          }
          goodsList(this.Qs.stringify(params)).then(() => {
            this.dialogFormVisible = false
            if (this.dialogStatus === 'creat') {
              this.$notify({
                title: 'Success',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Success',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
            }
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('您确定要删除该分类数据吗?', '提示', {
        type: 'warning'
      }).then(() => {
        console.log(row)
        goodsList(this.Qs.stringify({
          invoke_method: 'public_page_4m_insert_or_update_goods_type',
          pre_db_para_id_public_goods_type: row.id_public_goods_type,
          type_name: row.type_name,
          type_father: row.type_father,
          is_online: 111
        })).then(response => {
          console.log(response)
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
        this.getList()
      })
    },

    handleChange(item) {
      console.log(item)
      if (item.is_online === 0) {
        let params = {
          invoke_method: 'public_page_4m_insert_or_update_goods_type',
          pre_db_para_id_public_goods_type: item.id_public_goods_type,
          is_online: item.is_online,
        }
        goodsList(this.Qs.stringify(params)).then(() => {
          this.$notify({
            title: 'Success',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      } else {
        this.$confirm('您确定要下线该分类数据吗?','分类下线', {
          type: "warning"
        }).then(() => {
          let params = {
            invoke_method: 'public_page_4m_insert_or_update_goods_type',
            pre_db_para_id_public_goods_type: item.id_public_goods_type,
            is_online: item.is_online,
          }
          goodsList(this.Qs.stringify(params)).then(() => {
            this.$notify({
              title: 'Success',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
          this.getList()
        })
      }
    },

    handleTypeChild(item) {
      this.$router.push({name: 'TypeChildList', query: {id: item.id_public_goods_type, name: item.type_name}})
    },

    cancelDialog() {
      this.dialogFormVisible = false
      this.getList()
    },

    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>

</style>
